import { Entity } from "./Entity";
import { Passes } from "./Passes";

const ROOT_ = '__root__';
export class EntityManager {

    private instance_: EntityManager;

    private root_: Entity;
    private entitiesMap_: { [ key: string ]: Entity; };

    get Instance () {
        return this.instance_;
    }

    constructor () {

        if ( this.instance_ ) return this.instance_;

        this.entitiesMap_ = {};
        this.root_ = new Entity( ROOT_ );
        this.root_.Init();

        this.instance_ = this;

    }

    Remove ( name: string ) {
        delete this.entitiesMap_[ name ];
    }

    Get ( name: string ) {
        return this.entitiesMap_[ name ];
    }

    Add ( child: Entity, parent: Entity | undefined ) {

        this.entitiesMap_[ child.Name ] = child;

        // Root check
        if ( child.ID == this.root_.ID ) {
            return;
        } else {
            parent = parent || this.root_;
        }

        child.SetParent( parent );
    }

    Update ( elapsedTime: number ) {
        for ( let i = Passes.PASSES_MIN; i <= Passes.PASSES_MAX; i = i << 1 ) {
            this.UpdatePass_( elapsedTime, i );
        }
    }

    UpdatePass_ ( elapsedTime: number, pass ) {
        this.root_.Update( elapsedTime, pass );
    }
}
